package com.dsmbase.corp.flow.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.dsmbase.corp.common.Code;
import com.dsmbase.corp.common.ServiceException;
import com.dsmbase.corp.flow.dao.FlowBranchDao;
import com.dsmbase.corp.flow.dao.FlowDao;
import com.dsmbase.corp.flow.dao.FlowNodeDao;
import com.dsmbase.corp.flow.domain.Flow;
import com.dsmbase.corp.flow.domain.FlowBranch;
import com.dsmbase.corp.flow.domain.FlowNode;
import static com.dsmbase.corp.common.FlowUtil.*;

@Component
public class FlowService {

	@Autowired
	private FlowDao flowDao;
	
	@Autowired
	private FlowNodeDao flowNodeDao;
	
	@Autowired
	private FlowBranchDao flowBranchDao;
	
	public List<Flow> getAllFlow() {
		List<Flow> flowList = null;
		try {
			flowList = flowDao.getAllFlow();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return flowList;
	}
	
	public List<FlowNode> getFlowDefinitionNodes(Flow flow) throws ServiceException {
		FlowNode startNode = null;
		List<FlowNode> nodes = null;
		List<FlowBranch> branch = null;
		try {
			nodes = flowNodeDao.getAllFlowNodesByFlowId(flow.getId());
			branch = flowBranchDao.getFlowBranchByFlowId(flow.getId());
		} catch(SQLException e) {
			throw new ServiceException(Code.INVALID_FLOW_ID, e);
		}
		startNode = getStartNode(nodes, branch);
		List<FlowNode> nodeList = new ArrayList<FlowNode>();
		while (startNode != null) {
			nodeList.add(startNode);
			FlowNode nextNode = null;
			try {
				nextNode = flowNodeDao.getFlowNodeById(getNextNodeId(startNode, branch));
			} catch (SQLException e) {
				// TO-DO add log 
				// nextNode is null
			}
			startNode = nextNode;
		}
		return nodeList;
	}
	
	public FlowNode getFlowNodeById(int id) throws ServiceException{
		try {
			return flowNodeDao.getFlowNodeById(id);
		} catch (SQLException e) {
			// TODO log
			throw new ServiceException(Code.ILLEGAL_PARAM);
		}
	}

}
